package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.base.model.PageParams;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.content.mapper.*;
import com.xuecheng.content.model.dto.AddCourseDto;
import com.xuecheng.content.model.dto.CourseBaseInfoDto;
import com.xuecheng.content.model.dto.EditCourseDto;
import com.xuecheng.content.model.dto.QueryCourseParamsDto;
import com.xuecheng.content.model.po.*;
import com.xuecheng.content.service.CourseBaseInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class CourseBaseInfoServiceImpl implements CourseBaseInfoService {


    @Autowired
    private CourseBaseMapper courseBaseMapper;

    @Autowired
    private CourseMarketMapper courseMarketMapper;

    @Autowired
    private CourseCategoryMapper courseCategoryMapper;

    @Autowired
    private TeachplanMapper teachplanMapper;

    @Autowired
    private TeachplanMediaMapper teachplanMediaMapper;

    @Autowired
    private CourseTeacherMapper courseTeacherMapper;


    /*
     * @description 课程查询接口
     * @param pageParams 分页参数
     * @param queryCourseParamsDto 查询条件
     * @return com.xuecheng.base.model.PageResult<com.xuecheng.content.model.po.CourseBase>
     */
    @Override
    public PageResult<CourseBase> queryCourseBaseList(PageParams pageParams, QueryCourseParamsDto queryCourseParams) {
        //构建查询条件对象
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
        if (queryCourseParams != null) {

            if (queryCourseParams.getCourseName() != null) {
                //课程名字模糊查询
                queryWrapper.like(queryCourseParams.getCourseName() != null, CourseBase::getName, queryCourseParams.getCourseName());
            }
            if (queryCourseParams.getAuditStatus() != null && queryCourseParams.getAuditStatus().length() > 0) {
                //审核状态
                queryWrapper.eq(queryCourseParams.getAuditStatus() != null, CourseBase::getAuditStatus, queryCourseParams.getAuditStatus());
            }
            if (queryCourseParams.getPublishStatus() != null && queryCourseParams.getPublishStatus().length() > 0) {
                //发布状态
                queryWrapper.eq(queryCourseParams.getPublishStatus() != null, CourseBase::getStatus, queryCourseParams.getPublishStatus());
            }

        }


        //分页参数
        Page<CourseBase> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());

        //查询数据
        Page<CourseBase> pageResult = courseBaseMapper.selectPage(page, queryWrapper);

        //数据
        List<CourseBase> items = pageResult.getRecords();
        //总记录数
        long total = pageResult.getTotal();

        //准备返回数据 List<T> items, long counts, long page, long pageSize
        PageResult<CourseBase> courseBasePageResult = new PageResult<>(items, total, pageParams.getPageNo(), pageParams.getPageSize());

        return courseBasePageResult;
    }


    @Override
    @Transactional
    public CourseBaseInfoDto createCourseBase(Long companyId, AddCourseDto addCourseDto) {

        if (org.springframework.util.StringUtils.isEmpty(addCourseDto.getName())){
            XueChengPlusException.cast("课程名称为空");
        }

        //向课程基本信息表 course_base 写入数据
        //将传入页面的参数，放进courseBaseNew
        CourseBase courseBase = new CourseBase();
        //对象拷贝
        BeanUtils.copyProperties(addCourseDto, courseBase);
        courseBase.setCompanyId(companyId);
        courseBase.setCreateDate(LocalDateTime.now());
        //审核状态默认未提交
        courseBase.setAuditStatus("202002");
        //发布状态为未发布
        courseBase.setStatus("203001");

        //插入数据库
        int insert = courseBaseMapper.insert(courseBase);
        if (insert <= 0) {
            throw new RuntimeException("添加课程失败");
        }

        //向课程营销表 course_market 写入数据
        CourseMarket courseMarket = new CourseMarket();

        BeanUtils.copyProperties(addCourseDto, courseMarket);

        //获取刚才插入的 courseBase的 ID   因为这两个表是一对一关系
        Long courseId = courseBase.getId();

        courseMarket.setId(courseId);

        saveCourseMarket(courseMarket);


        CourseBaseInfoDto courseBaseInfo = getCourseBaseInfo(courseId);


        return courseBaseInfo;
    }

    private int saveCourseMarket(CourseMarket courseMarket) {

        //参数校验
        String charge = courseMarket.getCharge();
        if (StringUtils.isEmpty(charge)) {
            throw new RuntimeException("收费规则为空");
        }

        //如果课程收费，且没有填写价格，也报错
        if (charge.equals("201001")){
            if (courseMarket.getPrice()==null||courseMarket.getPrice()<=0){
                throw new RuntimeException("课程价格不能为空且必须大于0");
            }
        }

        //从数据库查询营销信息，存在更新，不存在添加
        Long id = courseMarket.getId();
        CourseMarket courseMarketOld = courseMarketMapper.selectById(id);
        if (courseMarketOld==null){
            //插入数据库
            int insert = courseMarketMapper.insert(courseMarket);
            return insert;
        }else {
            //将传入的数据，拷贝到courseMarketOld
            BeanUtils.copyProperties(courseMarket,courseMarketOld);
            courseMarketOld.setId(courseMarket.getId());
            //更新
            int res = courseMarketMapper.updateById(courseMarketOld);
            return res;
        }
    }

    //根据课程id查询课程基本信息，包括基本信息和营销信息
    public CourseBaseInfoDto getCourseBaseInfo(long courseId){

        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if(courseBase == null){
            return null;
        }
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        BeanUtils.copyProperties(courseBase,courseBaseInfoDto);
        if(courseMarket != null){
            BeanUtils.copyProperties(courseMarket,courseBaseInfoDto);
        }

        //查询分类名称
        CourseCategory courseCategoryBySt = courseCategoryMapper.selectById(courseBase.getSt());
        courseBaseInfoDto.setStName(courseCategoryBySt.getName());
        CourseCategory courseCategoryByMt = courseCategoryMapper.selectById(courseBase.getMt());
        courseBaseInfoDto.setMtName(courseCategoryByMt.getName());

        return courseBaseInfoDto;

    }


    @Override
    public CourseBaseInfoDto updateCourseBase(Long companyId, EditCourseDto editCourseDto) {

        //拿到课程ID
        Long courseId = editCourseDto.getId();
        //查询课程信息
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if (courseBase==null){
            XueChengPlusException.cast("课程不存在");
        }

        //数据合法性校验

        //根据实际的业务逻辑去校验

        //本机机构只能修改本机构的课程
        if (!companyId.equals(courseBase.getCompanyId())){
            XueChengPlusException.cast("本机构只能修改本机构的课程");
        }

        //封装数据
        BeanUtils.copyProperties(editCourseDto,courseBase);

        courseBase.setChangeDate(LocalDateTime.now());

        //更新数据库

        int i = courseBaseMapper.updateById(courseBase);
        if (i<=0){
            XueChengPlusException.cast("修改课程失败");
        }

        //查询课程信息
        CourseBaseInfoDto courseBaseInfo = getCourseBaseInfo(courseId);


        //修改营销信息
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);

        if (courseMarket==null){
            BeanUtils.copyProperties(editCourseDto,courseBase);
            int insert = courseMarketMapper.insert(courseMarket);
            if (insert<=0){
                XueChengPlusException.cast("课程营销信息修改失败");
            }
        }

        BeanUtils.copyProperties(editCourseDto,courseMarket);

        int i1 = courseMarketMapper.updateById(courseMarket);

        if (i1<=0){
            XueChengPlusException.cast("课程营销信息修改失败");
        }

        //查询修改后的营销信息
        CourseMarket courseMarket1 = courseMarketMapper.selectById(courseMarket.getId());

        BeanUtils.copyProperties(courseMarket1,courseBaseInfo);

        return courseBaseInfo;
    }


    @Override
    @Transactional
    public void deleteCourse(Long id) {
        CourseBase courseBase = courseBaseMapper.selectById(id);
        if (courseBase==null){
            XueChengPlusException.cast("课程不存在");
        }

        if (courseBase.getAuditStatus().equals("202002")){
            //删除课程需要删除课程相关的基本信息、营销信息、课程计划、课程教师信息。

            //删除课程营销信息
            int market = courseMarketMapper.deleteById(id);

            //删除课程计划
            LambdaQueryWrapper<Teachplan> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(Teachplan::getCourseId,id);
            int teachplan = teachplanMapper.delete(queryWrapper);

            //删除课程计划关联视频表
            LambdaQueryWrapper<TeachplanMedia> queryWrapper1=new LambdaQueryWrapper<>();
            queryWrapper1.eq(TeachplanMedia::getCourseId,id);
            int teachplanMedia = teachplanMediaMapper.delete(queryWrapper1);

            //删除课程教师信息
            LambdaQueryWrapper<CourseTeacher> queryWrapper2=new LambdaQueryWrapper<>();
            queryWrapper2.eq(CourseTeacher::getCourseId,id);
            int courseTeacher = courseTeacherMapper.delete(queryWrapper2);

            //删除课程基本信息

            int courseBaseInfo = courseBaseMapper.deleteById(id);

            if (teachplan<=0||courseTeacher<=0||courseBaseInfo<=0){
                XueChengPlusException.cast("课程删除失败");
            }

        }


    }


}
